/**   
* @Title: AbstractLocalCacheInitializer.java 
* @Package com.hundsun.hitop.base.cache 
* @Description: TODO(用一句话描述该文件做什么) 
* @author zjhua@hundsun.com   
* @date 2016年6月28日 上午11:17:22 
* @version V1.0   
*/ 
package com.medsoft.dlcache;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.web.context.ServletContextAware;

/**
 * @author zjhua
 *
 */
public abstract class AbstractLocalCacheInitializer implements ApplicationListener<ContextRefreshedEvent>,ServletContextAware {
	private ServletContext servletContext;
	
	@Autowired 
	private LocalCacheContainer localCacheContainer;
	
	boolean initLocalCache() {
		List<CacheEntry> cacheEntries = new ArrayList<CacheEntry>();
		cacheEntries.addAll(loadData());
		if(cacheEntries.size() == 0) {
			System.out.println("缓存为空，请检查初始化逻辑是否正确或者数据源是否为空！");
			return false;
		}
			
		ConcurrentHashMap<String, CacheEntry> cacheMap = new ConcurrentHashMap<String, CacheEntry>();
		
		for(CacheEntry cacheEntry : cacheEntries) {
			cacheMap.put(cacheEntry.getKey(), cacheEntry);
		}
		localCacheContainer.replaceCache(cacheEntries.get(0).getClass().getCanonicalName(), cacheMap);
		System.out.println("共加载" + cacheMap.size() + "条记录。");
		return true;
	}
	
	public abstract List<CacheEntry> loadData();

	/* (non-Javadoc)
	 * @see org.springframework.web.context.ServletContextAware#setServletContext(javax.servlet.ServletContext)
	 */
	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
	
	public ServletContext getServletContext() {
		return this.servletContext;
	}

	/* (non-Javadoc)
	 * @see org.springframework.context.ApplicationListener#onApplicationEvent(org.springframework.context.ApplicationEvent)
	 */
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		if (event.getApplicationContext().getParent() == null) {
			initLocalCache();
		}
	}
}
